# -*- coding:utf-8 -*-
# from win32com import client
# word = client.Dispatch("Word.Application")
# doc = word.Documents.Open("C:\\Users\\Administrator\\Desktop\\wordtest\\hetong.docx")
# doc.WebOptions.Encoding = 65001
# import pdb
# pdb.set_trace()
# doc.SaveAs("C:\\Users\\Administrator\\Desktop\\wordtest\\hetong.html", 8)
# with open('aa.html','r') as f:
#     print(f.read())

import docx
import codecs
from difflib import HtmlDiff
from bs4 import BeautifulSoup

file1 = docx.Document('v1.docx')
file2 = docx.Document('v2.docx')
obj = docx.Document()

para1 = ''
para2 = ''
max_paragraphs = max(len(file1.paragraphs),len(file2.paragraphs))
min_paragraphs = min(len(file1.paragraphs),len(file2.paragraphs))
for para in file1.paragraphs:
    para1 = para1 + para.text + '\n'
    print(para1)
for para in file2.paragraphs:
    para2 = para2 + para.text + '\n'
    print(para2)
delta_html = HtmlDiff().make_file(para1.splitlines(), para2.splitlines())
soup = BeautifulSoup(delta_html)
tr_s = soup.find("tbody").find_all("tr")
# import pdb
# pdb.set_trace()
for i in range(min_paragraphs):
    p_new = obj.add_paragraph()
    p1_org = file1.paragraphs[i]
    p2_org = file2.paragraphs[i]
    runs1 = p1_org.runs
    runs2 = p2_org.runs
    diff_adds = tr_s[i].find_all(class_="diff_add")
    diff_subs = tr_s[i].find_all(class_="diff_sub")
    for j in range(min(len(runs1),len(runs2))):
        if diff_adds and diff_adds[0].text in runs2[j].text:
            p_new.add_run(runs2[j].text,runs2[j].style)
            del(diff_adds[0])
        elif diff_subs and diff_subs[0].text in runs1[j].text:
            p_new.add_run(runs1[j].text,runs1[j].style)
            del(diff_subs[0])
        else:
            p_new.add_run(runs1[j].text,runs1[j].style)
    if len(runs1)>len(runs2):
        for j in range(min(len(runs1),len(runs2)),len(runs1)):
            p_new.add_run(runs1[j].text, runs1[j].style)
    else:
        for j in range(min(len(runs1), len(runs2)), len(runs2)):
            p_new.add_run(runs2[j].text, runs2[j].style)

obj.save("result.docx")








# with codecs.open('diff.html', 'w', encoding='utf-8') as f:
#     f.write(delta_html)
